package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @RequestMapping("/login")
    public Result login(HttpServletResponse response,@RequestBody Map map) {
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从redis中获取验证码
        Jedis resource = jedisPool.getResource();
        String s = resource.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        resource.close();
        if (s != null && validateCode != null && s.equals(validateCode)) {
            //验证码输入正确
            //判断当前是不是会员
           Member member=memberService.findByTelephone(telephone);
           if(member==null){
                member = new Member();
               //不是会员
               member.setRegTime(new Date());
               member.setPhoneNumber(telephone);
               memberService.add(member);
           }
            //向客户端浏览器写入Cookie,内容为手机号,目的跟踪用户
            Cookie cookie=new Cookie("login_member_telephone",telephone);
           //设置路径,这个是代表根路径下面的,都会有cookie,假如cookie.setPath("/pages");那表示只有pages下面的才有cookie
           cookie.setPath("/");
           //设置存活时间
            cookie.setMaxAge(60*60*24*30);
            //将cookie写入到浏览器中
            response.addCookie(cookie);
            //将会员信息保存到redis中
            String json = JSON.toJSON(member).toString();
            Jedis resource1 = jedisPool.getResource();
            resource1.setex(telephone,60*30,json);
            resource1.close();
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        } else {
            //验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
